package com.zx.dsptuneup_TriMic.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.zx.dsptuneup_TriMic.Adapter.MultiFragmentPagerAdapter;
import com.zx.dsptuneup_TriMic.App;
import com.zx.dsptuneup_TriMic.Base.BaseActivity;
import com.zx.dsptuneup_TriMic.Base.BaseFragment;
import com.zx.dsptuneup_TriMic.Base.NoScrollViewPager;
import com.zx.dsptuneup_TriMic.Data_Bean.DevicesDetailInfoBean;
import com.zx.dsptuneup_TriMic.Enum.MessageReceiveType;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.Tools.Constant;
import com.zx.dsptuneup_TriMic.Tools.EventMessage;
import com.zx.dsptuneup_TriMic.Util.Constants;
import com.zx.dsptuneup_TriMic.Util.StringUtil;
import com.zx.dsptuneup_TriMic.Util.ToastUtil;
import com.zx.dsptuneup_TriMic.Util.UserUtil;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.zx.dsptuneup_TriMic.fragment.InputFragment;
import com.zx.dsptuneup_TriMic.fragment.OutPutFragment;
import com.zx.dsptuneup_TriMic.network.DefaultObserver;
import com.zx.dsptuneup_TriMic.network.NetWorkManager;
import com.zx.dsptuneup_TriMic.widget.ui.LoadingView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import static com.zx.dsptuneup_TriMic.App.getContext;

/**
 * 单个控制页面
 * */
public class HomeActivity extends BaseActivity {
    @BindView(R.id.tab_title)
    TabLayout tabTitle;
    @BindView(R.id.inc_loading_view)
    LoadingView mILoadingView;
    @BindView(R.id.main_viewpager)
    NoScrollViewPager viewPager;
    @BindView(R.id.iv_search)
    ImageView rightView;
    @BindView(R.id.ic_nav)
    TextView back_home;
    @BindView(R.id.martrix_txt)
    TextView martrix_txt;


    /**点击返回时间*/
    private long time = 2000;
    private long first_time = 0;
    //viewPager会缓存的Fragment数量
    private static final int VIEWPAGER_OFF_SCREEN_PAGE_LIMIT = 2;
    private final String TAG = "HomeActivity.class";

    private List<BaseFragment> fragments = new ArrayList<>();
    private MultiFragmentPagerAdapter mPagerAdapter;

    private DevicesDetailInfoBean devicesDetailInfoBeans = new DevicesDetailInfoBean();

    private BaseFragment input = new InputFragment();
    private BaseFragment output = new OutPutFragment();

    private int groupId = -1;

    @Override
    protected void onResume() {
        super.onResume();
        if(UserUtil.isDevelopMode){
            martrix_txt.setVisibility(View.VISIBLE);
        }else {
            martrix_txt.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Intent intent = getIntent();
        String deviceId = intent.getStringExtra(Constant.addDevicesID);
        groupId = intent.getIntExtra(Constant.GroupID,0);

        initUI();
        requestData(deviceId);

        // 初始化发送指令
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Init.initData1();
//                }catch (Exception e){
//
//                }
//            }
//        }).start();
    }
    private void requestData(String deviceId) {
        //
        mILoadingView.showLoading();
        HashMap map = new HashMap();
        map.put("id",deviceId);
        //查询指定音频处理器数据
        NetWorkManager.getInstance().getNetWorkApiService().getDeviceInfoById(map).compose(HomeActivity.this.<BasicResponse<DevicesDetailInfoBean>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BasicResponse<DevicesDetailInfoBean>>() {
                    @Override
                    protected void onSuccess(BasicResponse<DevicesDetailInfoBean> response) {
                        if (response != null) {
                            mILoadingView.hideLoading();

                            devicesDetailInfoBeans = response.getData();
                            UserUtil.currentSingleGroup = devicesDetailInfoBeans.getGroup();
                            StringUtil.dealWithDevicesInfo(devicesDetailInfoBeans);


                            // 收取到数据后，再刷新下页面，显示数据
                            int position = Constants.channelEnum.line1;
                            //  发送事件
                            EventMessage msg = new EventMessage(MessageReceiveType.InputTitleIndexChange, position+"");
                            EventBus.getDefault().postSticky(msg);
                            Log.e(TAG,"data==="+response.getData());
                        }
                    }
                    @Override
                    protected void onFail(BasicResponse<DevicesDetailInfoBean> response) {
                        super.onFail(response);
                        mILoadingView.hideLoading();

                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        mILoadingView.hideLoading();
                    }
                });
    }


    protected void initUI() {
        ImmersionBar.with(this)
//                .transparentBar()
                .statusBarColor(R.color.home_bg)
                .statusBarDarkFont(false)
                .init();

        mPagerAdapter = new MultiFragmentPagerAdapter(getSupportFragmentManager());
        fragments.clear();
        fragments.add(input);
        fragments.add(output);
        mPagerAdapter.init(fragments);

        viewPager.setOffscreenPageLimit(VIEWPAGER_OFF_SCREEN_PAGE_LIMIT);
        viewPager.setAdapter(mPagerAdapter);

        viewPager.setCurrentItem(0);
        mPagerAdapter.getItem(0).setUserVisibleHint(true);
        tabTitle.setupWithViewPager(viewPager);
        tabTitle.setTabTextColors(Color.parseColor("#868686"), Color.parseColor("#E8E8E8"));
//        tabTitle.setTabTextColors(R.color.title_normal,R.color.black);
        // 无效
        tabTitle.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.title_select));

        setSelectTextBoldAndBig(Objects.requireNonNull(tabTitle.getTabAt(0)));
        initTabListener();

        //  设置
        rightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, SettingActivity.class);
                intent.putExtra(Constant.GroupID, groupId);
                startActivity(intent);
            }
        });
        // 音频矩阵
        martrix_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(devicesDetailInfoBeans.getMatrixlist() != null && devicesDetailInfoBeans.getMatrixlist().size()<1){
                    ToastUtil.makeText(HomeActivity.this,"请稍等!");
                    return;
                }

                Intent intent = new Intent(HomeActivity.this, MatrixActivity.class);
                intent.putExtra(Constant.GroupID, groupId);
                intent.putExtra(Constant.MatrixVoList, new Gson().toJson(devicesDetailInfoBeans.getMatrixlist()));
                startActivity(intent);
            }
        });

        back_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               finish();
            }
        });
    }


    private void initTabListener() {
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setSelectTextBoldAndBig(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.setCustomView(null);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void setSelectTextBoldAndBig(TabLayout.Tab tab) {
        TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.design_layout_tab_text, null);
        textView.setText(tab.getText());
        textView.setScaleY(1.1f);
        textView.setScaleX(1.1f);
//        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        textView.setTextColor(getResources().getColor(R.color.title_select));
        tab.setCustomView(textView);
    }

    // TODO
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("onPause","onPause called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.e("onDestroy","onDestroy called");
    }
}
